package com.ruoyi.web.controller.business.customer;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import com.ruoyi.business.base.PageParam;
import com.ruoyi.business.customer.domain.JbOpportunity;
import com.ruoyi.business.customer.domain.dto.JbCustomerDto;
import com.ruoyi.business.customer.domain.vo.JbOpportUnityAllocationDto;
import com.ruoyi.business.customer.domain.vo.JbOpportunityExcle;
import com.ruoyi.business.customer.domain.vo.JbOpportunityListVo;
import com.ruoyi.business.customer.service.JbCustomerService;
import com.ruoyi.business.customer.service.JbOpportunityService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.RoleEnum;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.web.core.JoR;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 商机 Controller
 *
 * @author ruoyi
 * @date 2024-10-11
 */
@Api("商机")
@RestController
@RequestMapping("/opportunity")
public class JbOpportunityController extends BaseController
{
    @Autowired
    private JbOpportunityService service;
    @Autowired
    private JbCustomerService customerService;

    /**
     * 查询商机列表
     */
    @ApiOperation("查询商机列表")
    @PreAuthorize("@ss.hasPermi('opportunity:list')")
    @GetMapping("/list")
    public TableDataInfo list(PageParam page, JbOpportunity jbOpportunity)
    {
//        IPage<JbOpportunity> iPage = service.page(page.b(), select);
        jbOpportunity.setOpportunityDataType(Constants.PUBLIC_NUMBER_0);
        IPage<JbOpportunityListVo> iPage = service.pageList(page, jbOpportunity);
        return JoR.getDataTable(iPage);

    }

    /**
     * 导出商机列表
     */
    @ApiOperation("导出商机列表")
    @PreAuthorize("@ss.hasPermi('opportunity:export')")
    @Log(title = "商机", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PageParam page, JbOpportunity jbOpportunity)
    {
        LambdaQueryWrapper<JbOpportunity> select = new LambdaQueryWrapper<>();
        IPage<JbOpportunity> iPage = service.page(page.b(), select);

        List<JbOpportunity> list = iPage.getRecords();
        ExcelUtil<JbOpportunity> util = new ExcelUtil<JbOpportunity>(JbOpportunity.class);
        util.exportExcel(response, list, "商机数据");
    }

    /**
     * 获取商机详细信息
     */
    @ApiOperation("获取商机详细信息")
    @PreAuthorize("@ss.hasPermi('opportunity:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(service.getById(id));
    }

    /**
     * 获取商机详细信息
     */
    @ApiOperation("获取商机详细信息")
    @PreAuthorize("@ss.hasAnyPermi('opportunity:getDetails,opportunity:getDeptDetails,opportunity:getTeamDetails,opportunity:getMyDetails')")
    @GetMapping(value = "/getDetails/{id}")
    public AjaxResult getDetails(@PathVariable("id") Long id)
    {
        return success(service.getInfo(id));
    }

    /**
     * 新增商机
     */
    @ApiOperation("新增商机")
    @PreAuthorize("@ss.hasPermi('opportunity:add')")
    @Log(title = "新增商机", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody JbOpportunity jbOpportunity)
    {
        return toAjax(service.save(jbOpportunity));
    }

    /**
     * 修改商机
     */
    @ApiOperation("修改商机")
    @PreAuthorize("@ss.hasPermi('opportunity:edit')")
    @Log(title = "修改商机", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody JbOpportunity jbOpportunity)
    {
        return toAjax(service.updateById(jbOpportunity));
    }

    /**
     * 删除商机
     */
    @ApiOperation("删除商机")
    @PreAuthorize("@ss.hasPermi('opportunity:remove')")
    @Log(title = "删除商机", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(service.removeByIds(Arrays.asList(ids)));
    }


    /**
     * 公共商机分配
     */
    @ApiOperation("公共商机分配")
    @PreAuthorize("@ss.hasPermi('opportunity:publicAllocation')")
    @Log(title = "公共商机分配", businessType = BusinessType.UPDATE)
    @PutMapping("/publicAllocation")
    public AjaxResult publicAllocation(JbOpportUnityAllocationDto jbOpportunity)
    {
        List<JbOpportunity> opportunities = Lists.newArrayList();
        if (ObjectUtils.isNotEmpty(jbOpportunity.getIds()))
        {
            jbOpportunity.getIds().stream().forEach(a ->
            {
                JbOpportunity upDeptId = new JbOpportunity();
                upDeptId.setId(a);
                upDeptId.setDepartmentId(jbOpportunity.getDepartmentId());
                upDeptId.setOpportunityDataType(Constants.PUBLIC_NUMBER_1);
                upDeptId.setDistributionType(Constants.PUBLIC_NUMBER_1.toString());
                upDeptId.setDistributionTime(new Date());
                opportunities.add(upDeptId);
            });
            return toAjax(service.updateBatchById(opportunities));
        }

        return toAjax(false);
    }

    /**
     * 查询商机列表
     */
    @ApiOperation("查询部门商机列表")
    @PreAuthorize("@ss.hasPermi('opportunity:deptList')")
    @GetMapping("/deptList")
    public TableDataInfo deptList(PageParam page, JbOpportunity jbOpportunity)
    {
        jbOpportunity.setOpportunityDataType(Constants.PUBLIC_NUMBER_1);
        Long deptId = getDeptId();
        jbOpportunity.setDepartmentId(deptId);
        IPage<JbOpportunityListVo> iPage = service.pageList(page, jbOpportunity);
        return JoR.getDataTable(iPage);

    }

    /**
     * 部门商机分配
     */
    @ApiOperation("部门商机分配")
    @PreAuthorize("@ss.hasPermi('opportunity:deptAllocation')")
    @Log(title = "部门商机分配", businessType = BusinessType.UPDATE)
    @PutMapping("/deptAllocation")
    public AjaxResult deptAllocation(JbOpportUnityAllocationDto jbOpportunity)
    {
        List<JbOpportunity> opportunities = Lists.newArrayList();
        if (ObjectUtils.isNotEmpty(jbOpportunity.getIds()))
        {
            jbOpportunity.getIds().stream().forEach(a ->
            {
                JbOpportunity upDeptId = new JbOpportunity();
                upDeptId.setId(a);
                upDeptId.setTeamId(jbOpportunity.getTeamId());
                upDeptId.setOpportunityDataType(Constants.PUBLIC_NUMBER_2);
                upDeptId.setDistributionType(Constants.PUBLIC_NUMBER_1.toString());
                upDeptId.setDistributionTime(new Date());
                opportunities.add(upDeptId);
            });
            return toAjax(service.updateBatchById(opportunities));
        }

        return toAjax(false);
    }

    /**
     * 部门商机领取
     */
    @ApiOperation("部门商机领取")
    @PreAuthorize("@ss.hasPermi('opportunity:deptReceive')")
    @Log(title = "部门商机领取", businessType = BusinessType.UPDATE)
    @PutMapping("/deptReceive")
    public AjaxResult deptReceive(JbOpportUnityAllocationDto jbOpportunity)
    {
        List<JbOpportunity> opportunities = Lists.newArrayList();
        if (ObjectUtils.isNotEmpty(jbOpportunity.getIds()))
        {
            jbOpportunity.getIds().stream().forEach(a ->
            {
                JbOpportunity upDeptId = new JbOpportunity();
                upDeptId.setId(a);
                upDeptId.setTeamId(jbOpportunity.getTeamId());
                upDeptId.setOpportunityDataType(Constants.PUBLIC_NUMBER_2);
                upDeptId.setDistributionType(Constants.PUBLIC_NUMBER_1.toString());
                upDeptId.setDistributionTime(new Date());
                opportunities.add(upDeptId);
            });
            return toAjax(service.updateBatchById(opportunities));
        }

        return toAjax(false);
    }

    /**
     * 查询商机列表
     */
    @ApiOperation("查询小组商机列表")
    @PreAuthorize("@ss.hasPermi('opportunity:teamList')")
    @GetMapping("/teamList")
    public TableDataInfo teamList(PageParam page, JbOpportunity jbOpportunity)
    {
        jbOpportunity.setOpportunityDataType(Constants.PUBLIC_NUMBER_2);
        Long deptId = getDeptId();
        jbOpportunity.setTeamId(deptId);
        IPage<JbOpportunityListVo> iPage = service.pageList(page, jbOpportunity);
        return JoR.getDataTable(iPage);

    }

    /**
     * 小组商机分配
     */
    @ApiOperation("小组商机分配")
    @PreAuthorize("@ss.hasPermi('opportunity:teamAllocation')")
    @Log(title = "小组商机分配", businessType = BusinessType.UPDATE)
    @PutMapping("/teamAllocation")
    public AjaxResult teamAllocation(JbOpportUnityAllocationDto jbOpportunity)
    {
        List<JbOpportunity> opportunities = Lists.newArrayList();
        if (ObjectUtils.isNotEmpty(jbOpportunity.getIds()))
        {
            jbOpportunity.getIds().stream().forEach(a ->
            {
                JbOpportunity upDeptId = new JbOpportunity();
                upDeptId.setId(a);
                upDeptId.setBusinessManagerId(jbOpportunity.getBusinessManagerId());
                upDeptId.setOpportunityDataType(Constants.PUBLIC_NUMBER_3);
                upDeptId.setDistributionStatus(Long.valueOf(Constants.PUBLIC_NUMBER_0));
                upDeptId.setDistributionType(Constants.PUBLIC_NUMBER_1.toString());
                upDeptId.setDistributionTime(new Date());
                opportunities.add(upDeptId);
            });
            return toAjax(service.updateBatchById(opportunities));
        }

        return toAjax(false);
    }

    /**
     * 小组商机领取
     */
    @ApiOperation("小组商机领取")
    @PreAuthorize("@ss.hasPermi('opportunity:teamReceive')")
    @Log(title = "小组商机领取", businessType = BusinessType.UPDATE)
    @PutMapping("/teamReceive")
    public AjaxResult teamReceive(JbOpportUnityAllocationDto jbOpportunity)
    {
        List<JbOpportunity> opportunities = Lists.newArrayList();
        if (ObjectUtils.isNotEmpty(jbOpportunity.getIds()))
        {
            jbOpportunity.getIds().stream().forEach(a ->
            {
                JbOpportunity upDeptId = new JbOpportunity();
                upDeptId.setId(a);
                upDeptId.setBusinessManagerId(jbOpportunity.getBusinessManagerId());
                upDeptId.setOpportunityDataType(Constants.PUBLIC_NUMBER_3);
                upDeptId.setDistributionStatus(Long.valueOf(Constants.PUBLIC_NUMBER_0));
                upDeptId.setDistributionType(Constants.PUBLIC_NUMBER_1.toString());
                upDeptId.setDistributionTime(new Date());
                opportunities.add(upDeptId);
            });
            return toAjax(service.updateBatchById(opportunities));
        }

        return toAjax(false);
    }

    /**
     * 我的商机列表
     */
    @ApiOperation("我的商机列表")
    @PreAuthorize("@ss.hasPermi('opportunity:myDataList')")
    @GetMapping("/myDataList")
    public TableDataInfo myDataList(PageParam page, JbOpportunity jbOpportunity)
    {
        jbOpportunity.setOpportunityDataType(Constants.PUBLIC_NUMBER_3);
        jbOpportunity.setBusinessManagerId(getUserId());
        IPage<JbOpportunityListVo> iPage = service.pageList(page, jbOpportunity);
        return JoR.getDataTable(iPage);

    }

    /**
     * 商机转为客户
     *
     * @param jbCustomerDto
     * @return
     */
    @ApiOperation("商机转为客户")
    @PreAuthorize("@ss.hasPermi('opportunity:becomeCustomer')")
    @Log(title = "商机转为客户", businessType = BusinessType.UPDATE)
    @PostMapping("/becomeCustomer")
    public AjaxResult becomeCustomer(@RequestBody JbCustomerDto jbCustomerDto)
    {
        Long id = customerService.saveInfo(jbCustomerDto);
        if (ObjectUtils.isNotEmpty(id))
        {
            return AjaxResult.success(id);
        }
        return AjaxResult.error();
    }

    /**
     * 商机导入
     *
     * @param file
     * @return
     * @throws Exception
     */
    @Log(title = "商机导入", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('opportunity:importData')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception
    {
        ExcelUtil<JbOpportunityExcle> util = new ExcelUtil<>(JbOpportunityExcle.class);
        List<JbOpportunityExcle> opportList = util.importExcel(file.getInputStream());
        boolean b = false;
        if (ObjectUtils.isNotEmpty(opportList))
        {
            b = service.importData(opportList);
        }
        return toAjax(b);
    }

    /**
     * 商机模版下载
     *
     * @param response
     * @param page
     * @param jbRawMaterialPrice
     */
    @Log(title = "商机模版下载", businessType = BusinessType.IMPORT)
    @PostMapping("/templateDownload")
    public void importData(HttpServletResponse response, PageParam page, JbOpportunity jbRawMaterialPrice)
    {
        List<JbOpportunityExcle> list = Lists.newArrayList();
        ExcelUtil<JbOpportunityExcle> util = new ExcelUtil<JbOpportunityExcle>(JbOpportunityExcle.class);
        util.exportExcel(response, list, "商机模版");
    }
}
